import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './CreateGroupModal.css';

interface User {
  _id: string;
  username: string;
  image: string;
}

interface CreateGroupModalProps {
  isVisible: boolean;
  onClose: () => void;
  currentUser: string;
  onGroupCreated: () => void;
}

const CreateGroupModal: React.FC<CreateGroupModalProps> = ({
  isVisible,
  onClose,
  currentUser,
  onGroupCreated,
}) => {
  const [groupName, setGroupName] = useState('');
  const [selectedMembers, setSelectedMembers] = useState<string[]>([]);
  const [availableUsers, setAvailableUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  // 获取可用的用户列表
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const response = await axios.get(
          `http://localhost:3001/ysx/users?currentUser=${currentUser}`
        );
        if (response.data.code === 200) {
          setAvailableUsers(response.data.data);
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        setError('获取用户列表失败');
      }
    };

    if (isVisible) {
      fetchUsers();
    }
  }, [isVisible, currentUser]);

  const handleMemberToggle = (username: string) => {
    setSelectedMembers(prev => {
      if (prev.includes(username)) {
        return prev.filter(name => name !== username);
      } else {
        return [...prev, username];
      }
    });
  };

  const handleCreateGroup = async () => {
    if (!groupName.trim()) {
      setError('请输入群聊名称');
      return;
    }

    if (selectedMembers.length < 1) {
      setError('请至少选择一个群成员');
      return;
    }

    // 确保创建者在成员列表中
    const allMembers = [...selectedMembers];
    if (!allMembers.includes(currentUser)) {
      allMembers.push(currentUser);
    }

    setLoading(true);
    setError('');

    try {
      // 由于我们使用用户名作为临时用户ID，直接使用用户名创建群聊
      // TODO: 后续需要修改为使用真实的用户ID
      console.warn('创建群聊数据:', {
        name: groupName.trim(),
        members: allMembers,
        createdBy: currentUser,
      });

      const response = await axios.post('http://localhost:3001/ysx/groups', {
        name: groupName.trim(),
        members: allMembers, // 直接使用用户名数组
        createdBy: currentUser, // 直接使用用户名
      });

      if (response.status === 201) {
        setGroupName('');
        setSelectedMembers([]);
        onGroupCreated();
        onClose();
      }
    } catch (error) {
      console.error('创建群聊失败:', error);
      const errorMessage =
        error instanceof Error ? error.message : '创建群聊失败';
      const responseError = (
        error as { response?: { data?: { msg?: string } } }
      )?.response?.data?.msg;
      setError(responseError || errorMessage);
    } finally {
      setLoading(false);
    }
  };

  if (!isVisible) return null;

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-content" onClick={e => e.stopPropagation()}>
        <div className="modal-header">
          <h3>创建群聊</h3>
          <button className="close-btn" onClick={onClose}>
            ×
          </button>
        </div>

        <div className="modal-body">
          <div className="form-group">
            <label>群聊名称</label>
            <input
              type="text"
              value={groupName}
              onChange={e => setGroupName(e.target.value)}
              placeholder="请输入群聊名称"
              maxLength={50}
            />
          </div>

          <div className="form-group">
            <label>选择群成员 ({selectedMembers.length}人)</label>
            <div className="members-list">
              {availableUsers.map(user => (
                <div
                  key={user._id}
                  className={`member-item ${selectedMembers.includes(user.username) ? 'selected' : ''}`}
                  onClick={() => handleMemberToggle(user.username)}
                >
                  <img
                    src={user.image}
                    alt={user.username}
                    className="member-avatar"
                  />
                  <span className="member-name">{user.username}</span>
                  {selectedMembers.includes(user.username) && (
                    <div className="checkmark">✓</div>
                  )}
                </div>
              ))}
            </div>
          </div>

          {error && <div className="error-message">{error}</div>}
        </div>

        <div className="modal-footer">
          <button className="btn btn-cancel" onClick={onClose}>
            取消
          </button>
          <button
            className="btn btn-create"
            onClick={handleCreateGroup}
            disabled={loading}
          >
            {loading ? '创建中...' : '创建群聊'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default CreateGroupModal;
